package io.cici.cc.mybatis.lite.reflection.wrapper;

import io.cici.cc.mybatis.lite.reflection.*;
import io.cici.cc.mybatis.lite.reflection.factory.ObjectFactory;
import io.cici.cc.mybatis.lite.reflection.invoker.Invoker;

import java.util.List;


public class BeanWrapper extends BaseWrapper {

    private final Object object;
    private final ClassMetaData classMetaData;

    public BeanWrapper(MetaDataObject metaDataObject, Object object) {
        super(metaDataObject);
        this.object = object;
        this.classMetaData = ClassMetaData.build(metaDataObject.getReflectorFactory(), object.getClass());
    }

    @Override
    public Object get(PropertyTokenizer prop) {
        if (prop.getIndex() != null) {
            Object collection = resolveCollection(prop, object);
            return getCollectionValue(prop, collection);
        }
        return getBeanProperty(prop, object);
    }

    @Override
    public void set(PropertyTokenizer prop, Object value) {
        if (prop.getIndex() != null) {
            Object collection = resolveCollection(prop, object);
            setCollectionValue(prop, collection, value);
        } else {
            setBeanProperty(prop, object, value);
        }
    }


    @Override
    public Class<?> getSetterType(String name) {
        PropertyTokenizer propertyTokenizer = new PropertyTokenizer(name);
        if (!propertyTokenizer.hasNext()) {
            return classMetaData.getSetterType(name);
        }
        MetaDataObject metaValue = metaDataObject.metaObjectForProperty(propertyTokenizer.getNameAndIndex());
        if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
            return classMetaData.getSetterType(name);
        }
        return metaValue.getSetterType(propertyTokenizer.getNext());
    }

    @Override
    public Class<?> getGetterType(String name) {
        PropertyTokenizer propertyTokenizer = new PropertyTokenizer(name);
        if (!propertyTokenizer.hasNext()) {
            return classMetaData.getGetterType(name);
        }
        MetaDataObject metaValue = metaDataObject.metaObjectForProperty(propertyTokenizer.getNameAndIndex());
        if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
            return classMetaData.getGetterType(name);
        }
        return metaValue.getGetterType(propertyTokenizer.getNext());
    }

    @Override
    public boolean hasSetter(String name) {
        PropertyTokenizer propertyTokenizer = new PropertyTokenizer(name);
        if (!propertyTokenizer.hasNext()) {
            return classMetaData.hasSetter(name);
        }
        if (classMetaData.hasSetter(propertyTokenizer.getNameAndIndex())) {
            MetaDataObject metaValue = metaDataObject.metaObjectForProperty(propertyTokenizer.getNameAndIndex());
            if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
                return classMetaData.hasSetter(name);
            }
            return metaValue.hasSetter(propertyTokenizer.getNext());
        }
        return false;
    }

    @Override
    public boolean hasGetter(String name) {
        PropertyTokenizer propertyTokenizer = new PropertyTokenizer(name);
        if (!propertyTokenizer.hasNext()) {
            return classMetaData.hasGetter(name);
        }
        if (classMetaData.hasGetter(propertyTokenizer.getNameAndIndex())) {
            MetaDataObject metaValue = metaDataObject.metaObjectForProperty(propertyTokenizer.getNameAndIndex());
            if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
                return classMetaData.hasGetter(name);
            }
            return metaValue.hasGetter(propertyTokenizer.getNext());
        }
        return false;
    }

    @Override
    public MetaDataObject instantiatePropertyValue(String name, PropertyTokenizer prop, ObjectFactory objectFactory) {
        MetaDataObject metaValue;
        Class<?> type = getSetterType(prop.getName());
        try {
            Object newObject = objectFactory.create(type);
            metaValue = MetaDataObject.forObject(newObject, metaDataObject.getObjectFactory(),
                    metaDataObject.getObjectWrapperFactory(), metaDataObject.getReflectorFactory());
            set(prop, newObject);
        } catch (Exception e) {
            throw new ReflectionException(
                    "Cannot set value of property '" + name + "' because '" + name
                            + "' is null and cannot be instantiated on instance of " + type.getName() + ". Cause:" + e,
                    e);
        }
        return metaValue;
    }

    private Object getBeanProperty(PropertyTokenizer prop, Object object) {
        try {
            Invoker method = classMetaData.getGetInvoker(prop.getName());
            try {
                return method.invoke(object, NO_ARGUMENTS);
            } catch (Throwable t) {
                throw ExceptionUtil.unwrapThrowable(t);
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Throwable t) {
            throw new ReflectionException(
                    "Could not get property '" + prop.getName() + "' from " + object.getClass() + ".  Cause: " + t, t);
        }
    }

    private void setBeanProperty(PropertyTokenizer prop, Object object, Object value) {
        try {
            Invoker method = classMetaData.getSetInvoker(prop.getName());
            Object[] params = {value};
            try {
                method.invoke(object, params);
            } catch (Throwable t) {
                throw ExceptionUtil.unwrapThrowable(t);
            }
        } catch (Throwable t) {
            throw new ReflectionException("Could not set property '" + prop.getName() + "' of '" + object.getClass()
                    + "' with value '" + value + "' Cause: " + t, t);
        }
    }

    @Override
    public boolean isCollection() {
        return false;
    }

    @Override
    public void add(Object element) {
        throw new UnsupportedOperationException();
    }

    @Override
    public <E> void addAll(List<E> list) {
        throw new UnsupportedOperationException();
    }

}
